package middleware

import (
	"api/internal/types"
	"fmt"
	jwt "github.com/golangblogs/jwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"golang.org/x/net/context"
	"net/http"
)

type TokenAuthTemplateMiddleware struct {
}

func NewTokenAuthTemplateMiddleware() *TokenAuthTemplateMiddleware {
	return &TokenAuthTemplateMiddleware{}
}

func (m *TokenAuthTemplateMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			resp := &types.Response{
				Code:    10001,
				Message: "token 未登录",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		j := jwt.NewJWT()
		parseToken, err := j.ParseToken(token)
		if err != nil {
			resp := &types.Response{
				Code:    10002,
				Message: "token is Invalid",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		fmt.Println("0000000000000000000000000", parseToken)
		//r.Form.Set("userId", parseToken.Id)
		cxt := context.WithValue(r.Context(), "userId", parseToken.ID)
		// Passthrough to next handler if need
		next(w, r.WithContext(cxt))
	}
}
